--
-- Author: ping.wang
-- Date: 2019-07-02 11:25:45
--
-- HankbookCombatPowerPanel
--

local ClassRef = app.mvc.createPanelClass(...)
local AvatarFactory = app:getClass("AvatarFactory")
local ListViewVertical = require("app.widget.listview.ListViewVertical")
local HandbookCombatPowerRender = import(".renders.HandbookCombatPowerRender")
local IconRender = require("app.widget.renders.IconRender")
local mathSin = math.sin
local mathCos = math.cos
local mathRad = math.rad
local table_insert = table.insert
local Armature = require("app.public.avatar.Armature")

--未满
local bgColor1 = cc.c4f(0.235,0.776,1,0.8)
local borderColor1 = cc.c4f(0.545,0.953,1,0.8)
--已满
local bgColor2 = cc.c4f(1,0.827,0.219,0.8)
local borderColor2 = cc.c4f(0.992,1,0.478,0.8)

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.HandbookCombatPowerPanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._playerPanel = self._ui.Panel_player
    self._playerNode = self._playerPanel:findChild("Node_position")

    self:_initPlayerPanel()
    self._changeBtn = self._playerPanel:findChild("selected_btn")
    self._changeBtn:addClickEventListener(function()
        local isBright = self._changeBtn:isBright()
        self._changeBtn:setBright(not isBright)
        self:_changeHeroClothes(isBright)
    end)

    local btn_tips = self._ui.Panel_bom:findChild("btn_tips")
    btn_tips:addClickEventListener(function()
        local posTemp = btn_tips:convertToWorldSpace(cc.p(0,0))
        local width, height = btn_tips:getContentSize2()
        posTemp.x = posTemp.x + width
        executeFunc(self._onOperate, "showDirectoryChallengeTips", posTemp)
    end)

    self._selBtn1 = self._ui.Panel_r:findChild("Panel_top/Button_1")
    self._selBtn2 = self._ui.Panel_r:findChild("Panel_top/Button_2")

    --默认显示左侧的
    self._showLeft = true
    self._selBtn1:setBright(not self._showLeft)
    self._selBtn2:setBright(self._showLeft)



    self._selBtn1:addClickEventListener(function()
        self._showLeft = true
        self:_showRightPanel()
    end)

    self._selBtn2:addClickEventListener(function()
        self._showLeft = false
        self:_showRightPanel()
    end)


    self._awards = {}
    for i = 1, 3 do
        local icon = self._ui.Panel_r:findChild(string.format("Panel_bom/Panel_icon/icon_%d",i))
        table.insert(self._awards, IconRender.create(icon))
    end

    self._getAwardBtn = self._ui.Panel_r:findChild("Panel_bom/Panel_icon/btn_enter")
    self._getAwardBtn:addClickEventListener(function()
        executeFunc(self._onOperate, "startGetChallengeAward")
        self:playStrengthSuccessAmi()
    end)

    self._curChallengeBar = self._ui.Panel_r:findChild("Panel_bom/Panel_icon/Panel_bar")
    self._panelMid = self._ui.Panel:findChild("Panel_r/Panel_mid")



    --初始化多边形对应文本此乃固定的
    for i = 1, 5 do
        local txt = self._panelMid:findChild("radar_1/text"..i)
        txt:setString(L(GD:getDirectoryChallengePropById(i).propName_short))
    end

    for i = 1, 6 do
        local txt = self._panelMid:findChild("radar_2/text"..i)
        txt:setString(L(GD:getDirectoryChallengePropById(i).propName_short))
    end


    local params = {
        renderClass = HandbookCombatPowerRender,
        perNum = 1,
        cellEventProxy = function(eventName, data)
            executeFunc(self._onOperate, eventName, data)
        end,
    }

    self._productList = ListViewVertical.new( self._ui.Panel_r:findChild("ScrollView"), params )

    self:_showRightPanel()

    self._playerPanel:findChild("Panel_1"):addClickEventListener(function()
        self:playNextAnimation()
    end)


    self:setContentSize( self._ui.Panel:getContentSize() )
    self:refresh()
end


function ClassRef:_showRightPanel()
    self._selBtn1:setBright(not self._showLeft)
    self._selBtn2:setBright(self._showLeft)

    if self._showLeft then
        self._ui.Panel_r:findChild("Panel_mid"):setVisible(true)
        self._ui.Panel_r:findChild("Panel_bom"):setVisible(true)
        self._productList:setVisible(false)
    else
        self._ui.Panel_r:findChild("Panel_mid"):setVisible(false)
        self._ui.Panel_r:findChild("Panel_bom"):setVisible(false)
        self._productList:setVisible(true)
    end
end

function ClassRef:_initPlayerPanel()
    self._playerNode:removeAllChildren()
    local params = UD:getAvatarParams()
    params.mountID = 0
    local armature = AvatarFactory.createHero(params, false)
    self._playerNode:addChild(armature)
    armature:setTag(0)
    self:playNextAnimation()
    --armature:play("mapidle")
    local player = UD:getPlayer()
    self._playerPanel:findChild("job_icon"):loadTexture(player:getClassIcon(2))
    self._playerPanel:findChild("name"):setString(UD:getNickName())
    self._playerPanel:findChild("job_name"):setString(player:getClassName())
    self._playerPanel:findChild("lv_num"):setString(UD:getLevel())
end

--改变角色外观
function ClassRef:_changeHeroClothes(bl)
    local heroParams = UD:getAvatarParams()
    heroParams.mountID = 0
    --todo
    if bl and self._data:getDropAtCurrentPw() then

        local drops = UD:parseDropToBagItem(self._data:getDropAtCurrentPw(), false, UD:getClass())
        if drops then
            --代表显示战力外观
            for k, v in pairs(drops) do
                heroParams.fashionIDs = GD:attachPreviewFashionId(heroParams.fashionIDs, v.tid)
            end
        end
    end

    self:performWithDelay(function()
        heroParams.inBattle = false
        local hero = AvatarFactory.createHero(heroParams)
        hero:setTag(0)
        self._playerNode:removeAllChildren()
        self._playerNode:addChild(hero)
        self:playNextAnimation()
    end, 0.2)

end

function ClassRef:refresh()
    if self._data then
        self:setVisible( true )

        local data = self._data
        local percent, percentStr = data:getProgressPwAndString()
        self._playerPanel:findChild("Panel_bom/lv"):setString(data:getCombatPowerLvName())
        self._playerPanel:findChild("Panel_bom/Panel_bar/LoadingBar"):setPercent(percent)
        self._playerPanel:findChild("Panel_bom/Panel_bar/num"):setString(percentStr)

        local lvConf = data:getLvInfo()
        if data:isMaxChallenge() and data.haveGet then
            --如果是最后一个挑战 并且已经领取过
            self._ui.Panel_r:findChild("Panel_bom/Panel_icon"):setVisible(false)
            self._ui.Panel_r:findChild("Panel_bom/Panel_max"):setVisible(true)
        else
            self._ui.Panel_r:findChild("Panel_bom/Panel_icon"):setVisible(true)
            self._ui.Panel_r:findChild("Panel_bom/Panel_max"):setVisible(false)


            local drops = UD:parseDropToBagItem(tonumber(lvConf.drop), false, UD:getClass())
            for k,v in ipairs(self._awards) do
                if k <= #drops then
                    v:setVisible(true)
                    v:setData(drops[k])
                    v:setTipEnable(true)
                else
                    v:setVisible(false)
                end
            end

            if data.canGet then
                --能领
                self._getAwardBtn:setVisible(true)
                self._curChallengeBar:setVisible(false)
            else
                --不能领
                self._getAwardBtn:setVisible(false)
                self._curChallengeBar:setVisible(true)

                local challengeCount = checknumber(lvConf.challengeNum)
                local perVal = 0
                for i=1,challengeCount do
                    if data:getPercentByIdx(i) == 1 then
                        perVal = perVal + 1
                    end
                end

                self._curChallengeBar:findChild("LoadingBar"):setPercent(perVal/challengeCount * 100)
                self._curChallengeBar:findChild("num"):setString(string.format("%d/%d",perVal,lvConf.challengeNum))
            end
        end

        local perData = {}
        local challengeCount = checknumber(lvConf.challengeNum)
        for i=1,challengeCount do
            table_insert(perData, data:getPercentByIdx(i))
        end

        if self._drawNode1 then
            self._drawNode1:removeFromParent()
            self._drawNode1 = nil
        end

        if self._drawNode2 then
            self._drawNode2:removeFromParent()
            self._drawNode2 = nil
        end

        self._ui.Panel_r:findChild("Panel_mid/tlt"):setString(L(lvConf.challengeTitle))
        if challengeCount == 5 then
            self._drawNode1 = cc.DrawNode:create()
            self._panelMid:findChild("radar_1/bg/radarNode"):addChild(self._drawNode1)

            self._panelMid:findChild("radar_1"):setVisible(true)
            self._panelMid:findChild("radar_2"):setVisible(false)
            self:_drawRadar(perData, 110, self._drawNode1, false)

        elseif challengeCount == 6 then
            self._drawNode2 = cc.DrawNode:create()
            self._panelMid:findChild("radar_2/bg/radarNode"):addChild(self._drawNode2)

            self._panelMid:findChild("radar_1"):setVisible(false)
            self._panelMid:findChild("radar_2"):setVisible(true)
            self:_drawRadar(perData, 104, self._drawNode2, false)
        end
        --type, percent, desc
        self._productList:reloadData(data:getChallengeData())
    else
        self:setVisible( false )
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

--画雷达图 可能是五边形 也可能是六边形
function ClassRef:_drawRadar(percentVals, radius, drawNode, isFinish)
    --local centerPos = cc.p(0,0)
    local pointNum = #percentVals
    local dxA = 360/pointNum
    local points = {}

    --五边形用
    if pointNum == 5 then
        for i = 1, pointNum do
            local a = dxA * (i - 1)
            local p = {}
            p.x = mathSin(mathRad(a)) * radius
            p.y = mathCos(mathRad(a)) * radius
            table.insert(points, p)
        end
    elseif pointNum == 6 then
        for i = 1, pointNum do
            local a = dxA * (i - 1.5)
            local p = {}
            p.x = mathSin(mathRad(a)) * radius
            p.y = mathCos(mathRad(a)) * radius
            table.insert(points, p)
        end
    end

    if isFinish then
        drawNode:drawPolygonFunc(points, {
            fillColor = bgColor2,
            borderWidth = 1,
            borderColor = borderColor2
        })
    else
        --上面得到了五边形 或者 六边形的顶点
        --接下来我们要确定相关的比例点
        --约定percentVals里面的值 >= 0 and <= 1
        local needPercent = 0

        local nPts = {}
        for k,v in ipairs(percentVals) do
            local p = points[k]
            table.insert(nPts, {x = needPercent * p.x + (1 - needPercent) * p.x * v, y = needPercent * p.y + (1 - needPercent) * p.y * v})
        end


        for i=1, #nPts do
            local tempPoints = {}
            table_insert(tempPoints, {x=0,y=0})
            table_insert(tempPoints, nPts[i])
            if i == #nPts then
                table_insert(tempPoints, nPts[1])
            else
                table_insert(tempPoints, nPts[i+1])
            end

            drawNode:drawTriangle(tempPoints[1],tempPoints[2],tempPoints[3],bgColor1)
            drawNode:drawSegment(tempPoints[2],tempPoints[3],1,borderColor1)
        end

        --[[drawNode:drawPolygonFunc(nPts, {
            fillColor = bgColor1,
            borderWidth = 1,
            borderColor = borderColor1
        })
        --]]
    end
end

local PlayerAnimations = {"mapidle","mapwalk","style1","mapmove","angry","celebrate","confusion","happy","seriously"}

function ClassRef:playNextAnimation()
    local hero = self._playerNode:getChildByTag(0)
    if hero then
        local animations = PlayerAnimations
        if not self._playIndex or self._playIndex >= #animations then
            self._playIndex = 0
        end
        self._playIndex = self._playIndex + 1
        hero:playAni({name=animations[self._playIndex],next=animations[1]})
    end
end

function ClassRef:playStrengthSuccessAmi()
    if not self._successArmature then
        local params = {
            armatureName = "QH1",
            path = Res.EquipStrengthSuccessAmi
        }
        local armature = Armature.create(params)
        armature:setPosition(0, 0)
        self._ui.Panel_r:findChild("Panel_mid/ani_node"):addChild(armature)
        self._successArmature = armature
    end
    self._successArmature:play("QH1", 1)
end

return ClassRef
